package cn.tedu.luban.settle.main.service;

import cn.tedu.luban.account.api.AccountApi;
import cn.tedu.luban.account.protocol.param.AccountPayParam;
import cn.tedu.luban.order.protocol.dto.OrderMessageDTO;
import cn.tedu.luban.settle.main.converter.SettleConverter;
import cn.tedu.luban.settle.main.repository.SettleRepository;
import cn.tedu.luban.settle.protocol.param.SettleBillParam;
import com.tedu.inn.protocol.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class SettleService { //100元 原价 平台20元 师傅80元
    @Autowired
    private SettleRepository settleRepository;
    @Autowired
    private SettleConverter settleConverter;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private AccountApi accountApi;
    public void settle(OrderMessageDTO orderMessageDTO) throws BusinessException {
        //考虑幂等 先查询订单是否已经存在账单了.
        String orderNo = orderMessageDTO.getOrderNo();
        if (StringUtils.isEmpty(orderNo)){
            log.error("结算失败,订单消息为空");
            return;
        }
        Long total = settleRepository.countSettleBillByOrderNo(orderNo);
        if (total>0){
            throw new BusinessException("10002","账单已经存在");
        }
        //1. 利用订单数据,传递数据比较完整的,生成和创建账单,一个订单数据可以绑定2个账单 师傅账单 平台账单
        List<SettleBillParam> params = settleConverter.dto2params(orderMessageDTO);
        //第一个元素是师傅账单 第二个元素是平台账单
        settleRepository.batchSave(params);
        //2. 从账单中找到是师傅账单,根据结算账单数据,给用户师傅进行打款操作.
        //userId orderNo totalAmount
        SettleBillParam workerBill = params.get(0);
        AccountPayParam payParam=new AccountPayParam();
        payParam.setUserId(workerBill.getWorkerId());
        payParam.setOrderNo(workerBill.getOrderNo());
        payParam.setTotalAmount(workerBill.getTotalAmount());
        accountApi.mockPayment(payParam);
        //3. 订单当前的状态,就从30-40 彻底完成 对订单的审核状态修改update 地哦啊用异步消息,让这两部也形成异步结构的格式
        //只需要发送一个包含了订单编号的消息,就可以协助订单服务完成状态的最终流转
        Message<String> message = MessageBuilder.withPayload(orderNo).build();
        //发送到order_complete_topic
        rocketMQTemplate.syncSend("order_complete_topic",message);
    }
}
